package com.njmaomao.gj.pyot.config;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 系统配置
 * @author hh
 *         2017年3月27日
 */
@Configuration
public class WechatRestTemplateConfig {

    private static final Logger log = LoggerFactory.getLogger(WechatRestTemplateConfig.class);

    @Bean
    public RestTemplate wechatRestTemplate() {
        HttpClient httpClient = HttpClientBuilder.create().setRetryHandler((exception, executionCount, context) -> {
            if (executionCount <= 3) {
                log.warn("restTemplate 调用异常:{}, 第{}次重试", exception.getMessage(), executionCount);
                return true;
            }
            return false;
        }).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

}
